package com.taotie.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.taotie.constant.MessageConstant;
import com.taotie.constant.StatusConstant;
import com.taotie.dto.DishDTO;
import com.taotie.dto.DishPageQueryDTO;
import com.taotie.entity.Dish;
import com.taotie.entity.DishFlavor;
import com.taotie.entity.Setmeal;
import com.taotie.exception.DeletionNotAllowedException;
import com.taotie.mapper.DishFlavorMapper;
import com.taotie.mapper.DishMapper;
import com.taotie.mapper.SetmealDishMapper;
import com.taotie.mapper.SetmealMapper;
import com.taotie.result.PageResult;
import com.taotie.service.DishService;
import com.taotie.vo.DishVO;
import com.taotie.vo.RandomDishVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 保存菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(
                    dishFlavor -> {
                        dishFlavor.setDishId(dishId);
                    }
            );
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * [批量]删除
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        ids.forEach(id -> {
                    Dish dish = dishMapper.getById(id);
                    //判断是否在起售中
                    if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                        throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                    }
                }
        );
        //判断当前菜品是否被套餐关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && !setmealIds.isEmpty()) {
            //被套餐关联了就抛出异常
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //执行到此便可正常删除

        //删除菜品表和口味表中的数据
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 更新菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        //删除本次口味数据，再添加修改后的口味数据，以达到修改要求
        List<Long> dishId=new ArrayList<>();
        dishId.add(dishDTO.getId());
        dishFlavorMapper.deleteByDishIds(dishId);
        //插入最新口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(id);
        // 封装成VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);

        return dishVO;
    }

    /**
     * 更新菜品状态
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
        // 如果菜品停售，需要把包含此菜品的套餐也停售
        if (StatusConstant.DISABLE.equals(status)) {
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && !setmealIds.isEmpty()) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(id)
                            .status(status)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public Dish getAll(String openid) {
        //获取该用户的偏好菜品Id
        List<Long> dishIdList = dishMapper.getDishId(openid);
        Random random = new Random();
        Long id = null;
        //随机获取列表中的一个索引下的dishId
        if (!dishIdList.isEmpty()) {
            int index= random.nextInt(dishIdList.size() + 1);
            id = dishIdList.get(index);
        }

        Dish dish = dishMapper.getById(id);
        return dish;
    }

    @Override
    public RandomDishVo randomDish() {
        long[] dishId = dishMapper.dishId();
        int index = new Random().nextInt(dishId.length);
        Dish dish = dishMapper.getById(dishId[index]);
        return new RandomDishVo(dish.getImage(), dish.getName());
    }

}
